package com.hmys.api.utils;

import com.alibaba.fastjson.JSON;
import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by chen365 on 2018/12/13.
 */
public class MapUtils {


    public static String formatParaMap(Map<String, Object> map) {
        StringBuffer sb = new StringBuffer();
        if (map.size() > 0) {
            for (String key : map.keySet()) {
                sb.append(key + "=");
                if (StringUtils.isEmpty(map.get(key))) {
                    sb.append("&");
                } else {
                    String value = String.valueOf(map.get(key));
                    try {
                        value = URLEncoder.encode(value, "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    sb.append(value + "&");
                }
            }
        }
        return sb.toString();
    }

    public static String getUrlParamByMap(Map<?, ?> map) {
        if (map.isEmpty()) {
            return null;
        }
        List<String> params = new ArrayList<>();
        for (Object key : map.keySet()) {
            String val = String.valueOf(map.get(key));
            if (!StringUtils.isEmpty(val)) {
                String para = key + "=" + val;
                params.add(para);
            }
        }
        String urlParam = String.join("&", params);
        if (params != null && params.size() > 0) {
            urlParam = "&" + urlParam;
        }
        return urlParam;
    }

    public static String getUrlParamByBean(Object bean) {
        Map<?, ?> map = objectToMap(bean);
        return getUrlParamByMap(map);
    }

    public static <T> T convertBean(Object object, Class<T> entityClass) {
        if (null == object) {
            return null;
        }
        return JsonUtils.json2Bean(JSON.toJSONString(object), entityClass);
    }

    public static Map<?, ?> objectToMap(Object object) {
        return convertBean(object, Map.class);
    }

}
